package com.yunda.nebula.gateway.controller;

import com.yunda.nebula.gateway.core.ListenerDto;
import com.yunda.nebula.gateway.core.entity.ConfigData;
import com.yunda.nebula.gateway.core.entity.FetchAppInfo;
import com.yunda.nebula.gateway.core.entity.Result;
import com.yunda.nebula.gateway.service.INotifyService;
import com.yunda.nebula.gateway.service.ITbGatewayAppService;
import com.yunda.nebula.gateway.wrapper.DeferredResultWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;

/**
 * \* User: wei.zhang
 * \* Date: 2020/9/17 20:56
 * \* Description:
 *
 * @author wei.zhang
 * \
 */
@Api(tags = "配置管理")
@RestController
@RequestMapping("/nebula/gateway/config")
public class GateWayConfigController {

    @Autowired
    private ITbGatewayAppService appService;

    @Autowired
    private INotifyService notifyService;

    @ApiOperation("获取app列表")
    @RequestMapping("/app.do")
    public Result apps(){
        List<String> appIds = appService.listApps();
        return Result.data(appIds);
    }

    @ApiOperation("获取app信息")
    @RequestMapping("/fetch.do")
    public Result fetch(String appId){
        ConfigData data = appService.fetch(appId);
        return Result.data(data);
    }

    @ApiOperation("获取app更新")
    @PostMapping("/listener.do")
    public DeferredResult<Result<FetchAppInfo>> listener(@RequestBody ListenerDto listenerDto){
        DeferredResultWrapper deferredResult = new DeferredResultWrapper(10000L);
        deferredResult.onTimeout(()->notifyService.remove(listenerDto.getAppId()));
        deferredResult.onCompletion(() -> notifyService.remove(listenerDto.getAppId()));

        notifyService.setResult(listenerDto.getAppId(),deferredResult);
        FetchAppInfo fetchAppInfo = appService.listener(listenerDto);
        if (fetchAppInfo != null){
            deferredResult.setResult(fetchAppInfo);
        }
        return deferredResult.getResult();
    }


}
